package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.domain.vo.NearUserVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.RecommendUserVo;
import com.itheima.domain.vo.VisitorVo;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MakeFriendManager {

    @Reference
    private RecommendUserService recommendUserService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private QuestionService questionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private VisitorService visitorService;

    @Reference
    private UserLocationService userLocationService;

    // 今日佳人
    public ResponseEntity findTodayBest() {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        RecommendUser recommendUser = recommendUserService.findMaxScore(userId);
        // 新用户，提供默认数据
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L); // 推荐用户id
            recommendUser.setScore(99D); // 双方缘分值
        }
        // 3.封装vo
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfoService.findById(recommendUser.getUserId())); // 推荐用户
        recommendUserVo.setFateValue(recommendUser.getScore().longValue()); // 缘分值

        // 4.返回结果
        return ResponseEntity.ok(recommendUserVo);
    }

    // 推荐用户列表
    public ResponseEntity findRecommendUser(Integer pageNum, Integer pageSize) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.根据用户id和分页查询推荐用户
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(pageNum, pageSize, userId);
        // 3.封装vo
        List<RecommendUserVo> voList = new ArrayList<>();
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 新用户，提供默认数据
        if (CollectionUtil.isEmpty(recommendUserList)) { // 今天一定有人写错的。。。 isEmpty isEmpty isEmpty
            for (int i = 2; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(i)); // 推荐用户id
                recommendUser.setScore(RandomUtil.randomDouble(40, 95));// 缘分值

                recommendUserList.add(recommendUser);
            }
        }
        // 遍历 recommendUserList 完成封装
        for (RecommendUser recommendUser : recommendUserList) {
            // 创建vo
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            recommendUserVo.setUserInfo(userInfoService.findById(recommendUser.getUserId())); // 推荐用户
            recommendUserVo.setFateValue(recommendUser.getScore().longValue()); // 缘分值
            // 设置到list
            voList.add(recommendUserVo);
        }
        // 4.返回分页对象
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity personalInfo(Long recommendUserId) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.根据推荐和登录用户id查询
        RecommendUser recommendUser = recommendUserService.findByRecommendUserIdAndUserId(recommendUserId, userId);
        // 如果没查到提供默认值
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(recommendUserId);
            recommendUser.setScore(RandomUtil.randomDouble(40, 95));
        }
        // 3.封装vo
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfoService.findById(recommendUser.getUserId()));
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        // 4.返回结果
        return ResponseEntity.ok(recommendUserVo);
    }

    // 查看陌生人问题（聊一下）
    public ResponseEntity strangerQuestions(Long recommendUserId) {
        // 1.根据推荐用户id查询
        Question question = questionService.findByUserId(recommendUserId);
        // 如果没查到提供默认值
        if (question == null) {
            question = new Question();
            question.setStrangerQuestion("你是喜欢GG还是MM？");
        }

        // 2.返回结果
        return ResponseEntity.ok(question.getStrangerQuestion());
    }

    // 最近访客
    public ResponseEntity visitors() {
        // 0.声明返回结果
        List<VisitorVo> voList = new ArrayList<>();
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.获取用户上次登录时间
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        // 3.根据用户id和上次登录时间查询
        if (StrUtil.isNotEmpty(lastAccessTime)) {
            List<Visitor> visitorList = visitorService.findByUserIdAndLastAccessTime(userId, lastAccessTime);

            // 4.封装vo
            if (CollectionUtil.isNotEmpty(visitorList)) {
                for (Visitor visitor : visitorList) {
                    // 创建vo
                    VisitorVo visitorVo = new VisitorVo();
                    // 设置userInfo
                    visitorVo.setUserInfo(userInfoService.findById(visitor.getVisitorUserId()));
                    // 设置缘分值
                    visitorVo.setFateValue(visitor.getScore().longValue());
                    // 添加voList中
                    voList.add(visitorVo);
                }
            }
        }

        // 5.记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        // 6.返回结果
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity saveUserLocation(double latitude, double longitude, String addrStr) {
        // 1.获取登录userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc保存或更新
        userLocationService.saveOrUpdateUserLocation(latitude, longitude, addrStr, userId);

        return ResponseEntity.ok(null);

    }

    public ResponseEntity searchNearUserVo(String gender, Integer distance) {
        // 1.获得登录人userId
        Long userId = UserHolder.get().getId();

        // 2.调用rpc查询
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);

        // 3.过滤
        List<NearUserVo> voList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {
                // 根据  nearUserId 查询用户信息
                UserInfo userInfo = userInfoService.findById(nearUserId);
                // 过滤自己
                if (userInfo.getId() == userId) {
                    continue;
                }
                // 过滤性别
                if (!StrUtil.equals(userInfo.getGender(), gender)) {
                    continue;
                }

                // 4.封装vo
                NearUserVo nearUserVo = new NearUserVo();
                nearUserVo.setUserId(userInfo.getId());
                nearUserVo.setNickname(userInfo.getNickname());
                nearUserVo.setAvatar(userInfo.getAvatar());

                voList.add(nearUserVo);

            }
        }
        // 5.返回结果
        return ResponseEntity.ok(voList);
    }
}
